package com.xunqi.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunqi.eduservice.entity.EduChapter;
import com.xunqi.eduservice.entity.EduCourse;
import com.xunqi.eduservice.entity.EduCourseDescription;
import com.xunqi.eduservice.mapper.EduCourseDescriptionMapper;
import com.xunqi.eduservice.mapper.EduCourseMapper;
import com.xunqi.eduservice.service.EduChapterService;
import com.xunqi.eduservice.service.EduCourseService;
import com.xunqi.eduservice.service.EduVideoService;
import com.xunqi.eduservice.vo.*;
import com.xunqi.servicebase.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 夏沫止水
 * @since 2020-07-31
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionMapper eduCourseDescriptionMapper;

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduChapterService eduChapterService;

    /**
     * 添加课程基本信息的方法
     * @param vo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveCourseInfo(CourseInfoVo vo) {

        //1、向课程表添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(vo,eduCourse);

        //添加到数据库
        int result = this.baseMapper.insert(eduCourse);
        if (result <= 0) {
            //添加失败
            throw new GuliException(20001,"添加课程信息失败");
        }

        //2、向课程简介表添加课程简介
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setId(eduCourse.getId());
        eduCourseDescription.setDescription(vo.getDescription());
        //2.1、添加课程简介信息到数据库
        int descResult = eduCourseDescriptionMapper.insert(eduCourseDescription);

        if (descResult <= 0) {
            //添加失败
            throw new GuliException(20001,"添加课程简介信息失败");
        }
        return eduCourse.getId();
    }

    /**
     * 根据课程id查询课程基本信息
     * @param courseId
     * @return
     */
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {

        CourseInfoVo courseInfoVo = new CourseInfoVo();

        //查询出课程信息
        EduCourse eduCourse = this.baseMapper.selectById(courseId);
        if (eduCourse == null) {
            throw new GuliException(20001,"课程信息不存在");
        }
        BeanUtils.copyProperties(eduCourse,courseInfoVo);

        //查询出课程简介信息
        EduCourseDescription description = eduCourseDescriptionMapper.selectById(eduCourse.getId());
        if (description == null) {
            throw new GuliException(20001,"课程简介信息不存在");
        }
        courseInfoVo.setDescription(description.getDescription());

        return courseInfoVo;
    }

    /**
     * 修改课程信息
     * @param courseInfoVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {

        //先修改课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int courseResult = this.baseMapper.updateById(eduCourse);
        if (courseResult <= 0) {
            throw new GuliException(20001,"课程信息修改失败");
        }

        //查询出课程简介信息
        EduCourseDescription description = eduCourseDescriptionMapper.selectById(eduCourse.getId());
        if (description == null) {
            throw new GuliException(20001,"课程简介信息不存在");
        }
        //修改课程简介信息
        description.setDescription(courseInfoVo.getDescription());
        int descResult = eduCourseDescriptionMapper.updateById(description);
        if (descResult <= 0) {
            throw new GuliException(20001,"课程简介信息修改失败");
        }
    }


    /**
     * 根据课程id查询课程详细信息
     * @param id
     * @return
     */
    @Override
    public CoursePublishVo publishCourseInfo(String id) {

        CoursePublishVo publishCourseInfo = this.baseMapper.getPublishCourseInfo(id);

        return publishCourseInfo;
    }

    /**
     * 多条件分页查询
     * @param page
     * @param limit
     * @param eduCourseVo
     * @return
     */
    @Override
    public IPage<EduCourse> pageCourseCondition(Long page, Long limit, EduCourseVo eduCourseVo) {

        //创建page对象
        Page<EduCourse> coursePage = new Page<>(page,limit);

        //构建查询条件
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();

        IPage<EduCourse> courseIPage = null;

        if (eduCourseVo == null) {
            courseIPage = this.baseMapper.selectPage(coursePage,queryWrapper);
            return courseIPage;
        }

        if (!StringUtils.isEmpty(eduCourseVo.getTitle())) {
            queryWrapper.eq("title",eduCourseVo.getTitle());
        }

        if (!StringUtils.isEmpty(eduCourseVo.getStatus())) {
            queryWrapper.eq("status",eduCourseVo.getStatus());
        }

        //排序
        queryWrapper.orderByDesc("gmt_create");

        courseIPage = this.baseMapper.selectPage(coursePage,queryWrapper);

        return courseIPage;
    }


    /**
     * 根据课程id删除课程信息
     * @param courseId
     */
    @Override
    public void removeCourse(String courseId) {

        //1、根据课程id删除小节
        boolean videoResult =  eduVideoService.removeVideoByCourseId(courseId);
        if (!videoResult) {
            throw new GuliException(20001,"删除课程小节失败");
        }

        //2、根据课程id删除章节
        boolean chapterResult = eduChapterService.remove(new QueryWrapper<EduChapter>().eq("course_id", courseId));
        if (!chapterResult) {
            throw new GuliException(20001,"删除课程章节失败");
        }

        //3、根据课程id删除课程描述
        int descResult = eduCourseDescriptionMapper.deleteById(courseId);
        if (descResult <= 0) {
            throw new GuliException(20001,"删除课程描述信息失败");
        }

        //4、根据课程id删除课程信息
        boolean courseResult = this.removeById(courseId);
        if (!courseResult) {
            throw new GuliException(20001,"删除课程信息失败");
        }
    }

    @Override
    public List<EduCourse> getTeacherIdByInfo(String teacherId) {

        List<EduCourse> eduCourses = this.baseMapper.selectList(new QueryWrapper<EduCourse>().eq("teacher_id", teacherId));

        return eduCourses;
    }

    @Override
    public Map<String, Object> getFrontCourseList(Page<EduCourse> coursePage, CourseFrontVo courseFrontVo) {

        //构建搜索条件
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        //判断条件是否为空，不为空就拼接
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) {     //一级分类
            queryWrapper.eq("subject_parent_id",courseFrontVo.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectId())) {        //二级分类
            queryWrapper.eq("subject_id",courseFrontVo.getSubjectId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) {        //关注度
            queryWrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) {        //最新时间
            queryWrapper.orderByDesc("gmt_create");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {        //价格
            queryWrapper.orderByDesc("price");
        }
        IPage<EduCourse> courseIPage = this.baseMapper.selectPage(coursePage, queryWrapper);

        List<EduCourse> records = courseIPage.getRecords();
        long total = courseIPage.getTotal();
        long current = courseIPage.getCurrent();
        long pages = courseIPage.getPages();
        long size = courseIPage.getSize();

        boolean hasNext = coursePage.hasNext();     //是否有下一页
        boolean hasPrevious = coursePage.hasPrevious();     //是否有上一页
        //把分页数据获取出来，放到map集合
        Map<String,Object> map = new HashMap<>();
        map.put("items",records);
        map.put("total",total);
        map.put("current",current);
        map.put("pages",pages);
        map.put("size",size);
        map.put("hasNext",hasNext);
        map.put("hasPrevious",hasPrevious);

        return map;
    }

    /**
     * 根据课程id查询课程详细信息
     * @param courseId
     * @return
     */
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {

        return this.baseMapper.getBaseCourseInfo(courseId);
    }

    @Override
    public boolean addBuyCount(String courseId) {

        EduCourse eduCourse = this.baseMapper.selectById(courseId);
        eduCourse.setBuyCount(eduCourse.getBuyCount() + 1);
        eduCourse.setViewCount(eduCourse.getViewCount() + 1);

        int result = this.baseMapper.updateById(eduCourse);

        return result > 0;

    }
}
